package com.mygame.game_server.mq;

import com.alibaba.fastjson.JSONObject;
import com.mygame.game_server.conf.AllConf;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息生产者
 */
public final class MqProducer {

    static  private final Logger logger = LoggerFactory.getLogger(MqProducer.class);
    /**
     *  消息生产者
     */
    private static DefaultMQProducer _mqProducer;
    /**
     * 构造器私有化
     */
    private MqProducer() {
    }

    /**
     * 初始化
     */
    public static void init() {
        try {
            DefaultMQProducer producer = new DefaultMQProducer(AllConf.GROUP_HEROSTORY);
            producer.setNamesrvAddr(AllConf.ROCKETMQ_SERVER_ADDR);
            producer.start();
            producer.setRetryTimesWhenSendAsyncFailed(3);;
            producer.setVipChannelEnabled(false);

            _mqProducer = producer;

            logger.info("消息队列生产者连接成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage(),ex);
        }
    }

    /**
     *  发送消息
     *
     * @param topic 主题
     * @param msg 消息
     */
    static public  void sendMsg(String topic,Object msg) {
        if (null == topic || null == msg) {
            return;
        }
        Message newMessage = new Message();
        newMessage.setTopic(topic);
        newMessage.setBody(JSONObject.toJSONBytes(msg));

        try {
            // 发送消息
            SendResult result = _mqProducer.send(newMessage);
            logger.info("信息发送成功");
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 获取生产者
     * @return DefaultMQProducer
     */
    public static DefaultMQProducer getInstance() {
        if (null == _mqProducer) {
            throw new RuntimeException("初始化失败");
        }
        return  _mqProducer;
    }
}
